<template>
  <ul class="list">
    <li class="item"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        @click="handleLetterClick"
      >{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    // json中cities数据放到letter数组中
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0
    }
  },
  updated () {
    // 获取字母A距离父元素距离
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    // 点击字母,子传父（city.vue）
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    // 拖动开始
    handleTouchStart () {
      this.touchStatus = true
    },
    // 拖动中
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // 当前元素距离顶部的距离-header和搜索栏的高度
          // 当前元素距离父元素距离
          const touchY = e.touches[0].clientY - 79
          // 当前元素处于第几个
          const index = Math.floor((touchY - this.startY) / 22)
          // 如果当前位置在字母表中
          if (index >= 0 && index < this.letters.length) {
            // 子传父
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    // 拖动结束
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl";
  .list
    display:flex
    flex-direction:column
    justify-content:center
    position:absolute
    right:0
    top:1.58rem
    bottom:0
    width: .4rem
    .item
      line-height: .44rem
      text-align: center
      color: $bgColor
</style>
